package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.openea.perpartner.common.core.enums.RabbitEnums;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.meily.rabbit.domain.BusinessDto;
import cn.openea.perpartner.meily.rabbit.factory.BusinessServiceFactory;
import cn.openea.perpartner.meily.rabbit.service.BusinessService;
import cn.openea.perpartner.meily.thirdparty.BpmSystemApi;
import cn.openea.perpartner.meily.web.entity.Customer;
import cn.openea.perpartner.meily.web.entity.PersonalInfo;
import cn.openea.perpartner.meily.web.entity.dto.SearchDto;
import cn.openea.perpartner.meily.web.entity.dto.SyncBPMAddressDTO;
import cn.openea.perpartner.meily.web.entity.vo.PersonalInfoSearchVo;
import cn.openea.perpartner.meily.web.mapper.PersonalInfoMapper;
import cn.openea.perpartner.meily.web.service.ICustomerService;
import cn.openea.perpartner.meily.web.service.IPersonalInfoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.beans.beancontext.BeanContextProxy;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * (PersonalInfo)表服务实现类
 *
 * @author rains
 * @since 2023-03-07 15:40
 */
@Transactional
@Slf4j
@Service("personalInfoService")
public class PersonalInfoServiceImpl extends ServiceImpl<PersonalInfoMapper, PersonalInfo> implements IPersonalInfoService, BusinessService {

    @Resource
    private BpmSystemApi bpmSystemApi;

    @Resource
    private ICustomerService customerService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 获取个人资料
     *
     * @param object 用户id或记录唯一id
     * @return 查询结果
     */
    @Override
    public AjaxResult getPersonalInfo(JSONObject object) {

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<PersonalInfo>();

        if (StrUtil.isNotBlank(object.getString("userId"))) {
            wrapper.eq(PersonalInfo::getUserId, object.getString("userId"));
        }

        if (StrUtil.isNotBlank(object.getString("id"))) {
            wrapper.eq(PersonalInfo::getId, object.getString("id"));
        }

        PersonalInfo personalInfo = getOne(wrapper);

        /**
         * 2023-06-13 add by lys
         *
         * 增加参数，为了区分BPM与小程序请求
         *  method = 'bpm'，则表示为BPM的请求
         *
         * 测评师导出素材时需要查询测评师资料，为了不返回null，特做以下处理
         */
        if("bpm".equals(object.getString("method"))){
            if(BeanUtil.isEmpty(personalInfo)){
                personalInfo = new PersonalInfo();
                LambdaQueryWrapper<Customer> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Customer::getUserId, object.getString("userId"));
                Customer customer = customerService.getOne(wrapper1);
                if(BeanUtil.isNotEmpty(customer)){
                    BeanUtil.copyProperties(customer, personalInfo);
                    personalInfo.setId(null);
                }
            }
        }

        return AjaxResult.success("获取个人资料成功！", personalInfo);
    }

    /**
     * 更新个人资料
     * 说明：包含新增、修改
     *
     * @param personalInfo 实例对象
     * @return 更新结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(PersonalInfo personalInfo) {

        /**
         * 第1步 数据处理
         */
        // --------------start---------字段去重处理---------------start-------------------
        // 兴趣领域去重处理
        String interests = personalInfo.getInterests();
        if (StringUtils.isNotBlank(interests)) {
            String[] arr = interests.split(",");
            Set<String> set = new HashSet<>();
            Collections.addAll(set, arr);
            interests = StringUtils.join(set, ",");
            personalInfo.setInterests(interests);
        }

        // 测评喜好【主】品类去重处理
        String mainCategory = personalInfo.getMainCategory();
        if (StringUtils.isNotBlank(mainCategory)) {
            String[] arr = mainCategory.split(",");
            Set<String> set = new HashSet<>();
            Collections.addAll(set, arr);
            mainCategory = StringUtils.join(set, ",");
            personalInfo.setMainCategory(mainCategory);
        }

        // 测评喜好【副】品类去重处理
        String secondCategory = personalInfo.getSecondCategory();
        if (StringUtils.isNotBlank(secondCategory)) {
            String[] arr = secondCategory.split(",");
            Set<String> set = new HashSet<>();
            Collections.addAll(set, arr);
            secondCategory = StringUtils.join(set, ",");
            personalInfo.setSecondCategory(secondCategory);

        }
        // --------------end---------字段去重处理---------------end------------------

        /**
         * 第2步 更新个人资料（新增还是修改）
         */
        if (StrUtil.isBlank(personalInfo.getId())) {
            // 如果“个人资料记录唯一id”为空，则表示新增，可直接保存
            if (!save(personalInfo)) {
                return AjaxResult.error("更新个人资料失败！");
            }
        } else {
            if (!updateById(personalInfo)) {
                return AjaxResult.error("更新个人资料失败！");
            }
        }
        /**
         * 第3步 同步收货地址到BPM的收货地址记录表（Archives_Address）
         */
        // 地址不为空，才需要同步
        if (StrUtil.isNotBlank(personalInfo.getRegion()) && StrUtil.isNotBlank(personalInfo.getStreetVillage()) && StrUtil.isNotBlank(personalInfo.getAddress())) {
            bpmSystemApi.syncAddress(SyncBPMAddressDTO.builder()
                    .userId(personalInfo.getUserId())
                    .userName(personalInfo.getUserName())
                    .realName(personalInfo.getUserName())
                    .phoneNumber(personalInfo.getPhoneNumber())
                    .region(personalInfo.getRegion())
                    .streetVillage(personalInfo.getStreetVillage())
                    .address(personalInfo.getAddress())
                    .build());
        }

        /**
         * 第4步 判断测评师资料是否全部填写完毕
         * @param obj_old   测评师资料对象
         * @return flag
         */
        String msg = "资料已同步更新！";
        boolean flag = personalInfoCompleted(personalInfo);
        if (!flag) {
            msg = "资料已同步更新，还有部分未填写哦~";
        }

        /**
         *
         * 2023-05-08 add by lys
         *
         * 第5步 增加与基本信息的关联
         */
        LambdaUpdateWrapper<Customer> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Customer::getUserId, personalInfo.getUserId());
        updateWrapper.set(Customer::getEvaluatorId, personalInfo.getId());
        if(!customerService.update(updateWrapper)){
            throw new ServiceException("增加与基本信息的关联出错了！");
        }

        return AjaxResult.success(msg, personalInfo);

    }

    /**
     * 获取个人资料列表---分页
     *
     * @return 查询结果
     */
    @Override
    public List<PersonalInfo> getPersonalInfoList(SearchDto searchDto) {
        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();

        String searchStr = searchDto.getSearchStr();
        if (StrUtil.isNotBlank(searchStr)) {
            wrapper.and(wrap -> wrap.like(PersonalInfo::getUserId, searchStr)
                    .or().like(PersonalInfo::getUserName, searchStr)
                    .or().like(PersonalInfo::getRealName, searchStr)
                    .or().like(PersonalInfo::getMainCategory, searchStr)
                    .or().like(PersonalInfo::getSecondCategory, searchStr));
        }

        wrapper.orderByDesc(PersonalInfo::getCreateTime);
        return list(wrapper);
    }

    /**
     * 【测评】获取热门测评师
     * 标题=平台昵称；岗位=身份职业；标签=测评喜好主类目+副类目 （不能为空）
     *
     * @return 查询结果
     */
    @Override
    public AjaxResult getPopularEvaluators() {

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();

        wrapper.ne(PersonalInfo::getUserName, "");
        wrapper.ne(PersonalInfo::getIdentityJob, "");
        wrapper.ne(PersonalInfo::getMainCategory, "");
        wrapper.ne(PersonalInfo::getSecondCategory, "");

        wrapper.last("ORDER BY RAND() limit 5");

        return AjaxResult.success("获取热门测评师成功！", list(wrapper));

    }

    /**
     * 【测评】获取测评师---换一批
     *
     * @param object count需要获取多少条数据
     * @return 查询结果
     */
    @Override
    public AjaxResult changeEvaluators(JSONObject object) {

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();

        wrapper.ne(PersonalInfo::getUserName, "");
        wrapper.ne(PersonalInfo::getUserName, "微信用户");
        wrapper.ne(PersonalInfo::getIdentityJob, "");
        wrapper.ne(PersonalInfo::getMainCategory, "");
        wrapper.ne(PersonalInfo::getSecondCategory, "");

        wrapper.last("ORDER BY RAND() limit " + object.getInteger("count"));

        return AjaxResult.success("获取测评师（换一批）成功！", list(wrapper));
    }

    /**
     * 【测评】获取测评师列表---分页
     *
     * @param object count需要获取多少条数据
     * @return 查询结果
     */
    @Override
    public List<PersonalInfo> getEvaluatorsList(JSONObject object) {

        // 固定种子
        String swab = StrUtil.isNotBlank(object.getString("swab")) ? object.getString("swab") : String.valueOf(getRandomIntRange(2, 10));// 搜索内容（条件）
        String searchStr = object.getString("searchStr");

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();

        wrapper.ne(PersonalInfo::getUserName, "");
        wrapper.ne(PersonalInfo::getUserName, "微信用户");
        wrapper.ne(PersonalInfo::getIdentityJob, "");
        wrapper.ne(PersonalInfo::getMainCategory, "");
        wrapper.ne(PersonalInfo::getSecondCategory, "");

        if (StrUtil.isNotBlank(searchStr)) {
            wrapper.and(wrap -> wrap.like(PersonalInfo::getUserId, searchStr)
                    .or().like(PersonalInfo::getUserName, searchStr)
                    .or().like(PersonalInfo::getIdentityJob, searchStr)
                    .or().like(PersonalInfo::getMainCategory, searchStr)
                    .or().like(PersonalInfo::getSecondCategory, searchStr));
        }

        wrapper.last("ORDER BY RAND(" + swab + ") ");

        return list(wrapper);

    }

    /**
     * 【测评】校验测评师资料是否填写完毕
     *
     * @param object 用户id
     * @return 查询结果
     */
    @Override
    public AjaxResult CheckEvaluatorInfo(JSONObject object) {
        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PersonalInfo::getUserId, object.getString("userId"));
        PersonalInfo personalInfo = getOne(wrapper);

        if (BeanUtil.isEmpty(personalInfo)) {
            return AjaxResult.success("调用校验测评师资料是否填写完毕的接口成功！", false);
        }

        /*----------基本信息 不校验----------
        平台ID(userId)：0329032126655470
        平台昵称(userName)：Emma
        关联手机(phoneNumber)：13535569382
        真实姓名(realName)：梁小婷
        性别(sex)：女
        年龄层(ageGroup)：80后
        所在地区(region)：广东省-广州市-天河区
        所在街道(streetVillage)：新塘街道-新塘社区居委会
        收货地址(address)：万科云城米酷公寓
        身份职业(identityJob)：在职宝妈/宝爸
        月收入(monthlyIncome)：1w以上
        ----------玫丽测评师----------
        测评喜好（1个主类目）(mainCategory)：不变
        测评喜好（3个副类目）(SecondCategory)：不变
        兴趣领域（多选）(Interests)：不变
        抖音平台(TikTok)：有
        抖音粉丝数(TikTokFans)：1-49
        抖音获赞数(TikTokLikes)：1-49
        小红书平台(LittleRedBook)：有
        小红书粉丝数(LittleRedBookFans)：1-49
        小红书获赞与收藏数(LittleRedBookLikes)：1-49
        其他社交平台(OtherPlatforms)（选填，不用检验）：无
        */

        if (StrUtil.isBlank(personalInfo.getMainCategory()) || StrUtil.isBlank(personalInfo.getSecondCategory()) || StrUtil.isBlank(personalInfo.getInterests())) {
            return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", false);
        }

        if (StrUtil.isBlank(personalInfo.getTiktok()) || StrUtil.isBlank(personalInfo.getLittleRedBook())) {
            return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", false);
        }

        // 判断是否有抖音，有，则检验粉丝数、获赞数
        if ("有".equals(personalInfo.getTiktok())) {
            // System.out.println("****进入判断是否有抖音***");
            if (StrUtil.isBlank(personalInfo.getTiktokFans()) || StrUtil.isBlank(personalInfo.getTiktokLikes())) {
                return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", false);
            }
        }

        // 判断是否有小红书，有，则检验粉丝数、获赞数、收藏量
        if ("有".equals(personalInfo.getLittleRedBook())) {
            // System.out.println("****进入判断是否有小红书***");
            if (StrUtil.isBlank(personalInfo.getLittleRedBookFans()) || StrUtil.isBlank(personalInfo.getLittleRedBookLikes())) {
                return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", false);
            }
        }

        /*// 遍历JSONObject时，跳过以下字段
        String FieldNames = "id,createTime,updateTime,tiktokFans,tiktokLikes,littleRedBookFans,littleRedBookLikes,evaluationGrade,shoppingGroup,potentialConsumer,willingDistribute,openid,unionid,subscriptionOpenid,OtherPlatforms";

        JSONObject infoObject = JSON.parseObject(JSON.toJSONString(personalInfo), JSONObject.class);

        // 遍历JSONObject
        Iterator iter = infoObject.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
            String key = entry.getKey().toString();
            if (FieldNames.contains(key)) {
                // System.out.println("****是否跳过以下字段***key=" + key);
                continue;
            }

            if (entry.getValue() != null) {
                String value = entry.getValue().toString();
                // System.out.println("********"+ value + "=" + value);
                if (StrUtil.isBlank(value)) {
                    return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", false);
                }
            } else {
                return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", false);
            }
        }*/

        return AjaxResult.success("调用测评师资料是否填写完毕的接口成功！", true);
    }

    /**
     * 【线上服务商】校验资料线上服务商是否填写完毕
     *
     * @param object 用户id
     * @return 查询结果
     */
    @Override
    public AjaxResult checkProviderInfo(JSONObject object) {

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PersonalInfo::getUserId, object.getString("userId"));
        PersonalInfo personalInfo = getOne(wrapper);

        if (BeanUtil.isEmpty(personalInfo)) {
            return AjaxResult.success("调用校验线上服务商资料是否填写完毕的接口成功！", false);
        }

        /*----------基本信息----------
        平台ID(userId)：0329032126655470
        平台昵称(userName)：Emma
        关联手机(phoneNumber)：13535569382
        真实姓名(realName)：梁小婷
        性别(sex)：女
        年龄层(ageGroup)：80后
        所在地区(region)：广东省-广州市-天河区
        所在街道(streetVillage)：新塘街道-新塘社区居委会
        收货地址(address)：万科云城米酷公寓
        身份职业(identityJob)：在职宝妈/宝爸
        月收入(monthlyIncome)：1w以上
        ----------线上服务商----------
        覆盖团购群（个）(shoppingGroup)：1-3
        潜在消费群体（人）(potentialConsumer)：1-49
        */

        JSONObject obj = new JSONObject();
        obj.put("userId", personalInfo.getUserId());
        obj.put("userName", personalInfo.getUserName());
        obj.put("phoneNumber", personalInfo.getPhoneNumber());
        obj.put("realName", personalInfo.getRealName());
        obj.put("sex", personalInfo.getSex());
        obj.put("ageGroup", personalInfo.getAgeGroup());
        obj.put("region", personalInfo.getRegion());
        obj.put("streetVillage", personalInfo.getStreetVillage());
        obj.put("address", personalInfo.getAddress());
        obj.put("identityJob", personalInfo.getIdentityJob());
        obj.put("monthlyIncome", personalInfo.getMonthlyIncome());
        obj.put("shoppingGroup", personalInfo.getShoppingGroup());
        obj.put("potentialConsumer", personalInfo.getPotentialConsumer());

        // 遍历JSONObject
        Iterator iter = obj.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
            String key = entry.getKey().toString();
            if (entry.getValue() != null) {
                String value = entry.getValue().toString();
                // BeanCtx.out("********"+ value + "=" + value);
                if (StrUtil.isBlank(value)) {
                    return AjaxResult.success("调用校验线上服务商资料是否填写完毕的接口成功！", false);
                }
            } else {
                return AjaxResult.success("调用校验线上服务商资料是否填写完毕的接口成功！", false);
            }
        }

        return AjaxResult.success("调用校验线上服务商资料是否填写完毕的接口成功！", true);
    }

    /**
     * 第4步 判断个人资料是否全部填写完毕
     *
     * @param personalInfo 个人资料对象
     * @return flag
     */
    public boolean personalInfoCompleted(PersonalInfo personalInfo) {

        if (StrUtil.isBlank(personalInfo.getMainCategory()) || StrUtil.isBlank(personalInfo.getSecondCategory()) || StrUtil.isBlank(personalInfo.getInterests())) {
            return false;
        }

        if (StrUtil.isBlank(personalInfo.getTiktok()) || StrUtil.isBlank(personalInfo.getLittleRedBook())) {
            return false;
        }

        // 判断是否有抖音，有，则检验粉丝数、获赞数
        if ("有".equals(personalInfo.getTiktok())) {
            // BeanCtx.out("****进入判断是否有抖音***");
            String TikTokFans = personalInfo.getTiktokFans();
            String TikTokLikes = personalInfo.getTiktokLikes();
            if (StrUtil.isBlank(TikTokFans) || StrUtil.isBlank(TikTokLikes)) {
                return false;
            }
        }

        // 判断是否有小红书，有，则检验粉丝数、获赞数、收藏量
        if ("有".equals(personalInfo.getLittleRedBook())) {
            // BeanCtx.out("****进入判断是否有小红书***");
            String LittleRedBookFans = personalInfo.getLittleRedBookFans();
            String LittleRedBookLikes = personalInfo.getLittleRedBookLikes();
            if (StrUtil.isBlank(LittleRedBookFans) || StrUtil.isBlank(LittleRedBookLikes)) {
                return false;
            }
        }

        // 遍历JSONObject时，跳过以下字段
        String FieldNames = "id,createTime,updateTime,tiktok,tiktokFans,tiktokLikes,littleRedBook,littleRedBookFans,littleRedBookLikes,evaluationGrade,willingDistribute,openid,unionid,subscriptionOpenid,OtherPlatforms";

        JSONObject object = JSON.parseObject(JSON.toJSONString(personalInfo), JSONObject.class);

        // 遍历JSONObject
        Iterator iter = object.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
            String key = entry.getKey().toString();
            if (FieldNames.contains(key)) {
                // BeanCtx.out("****是否跳过以下字段***key=" + key);
                continue;
            }

            if (entry.getValue() != null) {
                String value = entry.getValue().toString();
                // BeanCtx.out("********"+ value + "=" + value);
                if (StrUtil.isBlank(value)) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }


    /**
     * 根据用户id修改测评师等级
     *
     * @param object 用户id、测评师等级
     */
    @Override
    public AjaxResult updateEvaluationGradeByUserId(JSONObject object) {

        LambdaUpdateWrapper<PersonalInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PersonalInfo::getUserId, object.getString("userId"));
        updateWrapper.set(PersonalInfo::getEvaluationGrade, object.getString("evaluationGrade"));

        if (!update(updateWrapper)) {
            return AjaxResult.error("修改测评等级出错了！");
        }

        return AjaxResult.success("修改测评等级成功！");
    }

    /** ********************* 以下是后台管理用到的 ******************************* */

    /**
     * 根据用户id获取个人资料
     *
     * @param userId 用户id或记录唯一id
     * @return 查询结果
     */
    @Override
    public PersonalInfo getPersonalInfoByUserId(String userId) {

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<PersonalInfo>();

        if (StrUtil.isNotBlank(userId)) {
            wrapper.eq(PersonalInfo::getUserId, userId);
        }

        return getOne(wrapper);

    }

    @Override
    public List<PersonalInfo> getListBySearchVo(@NonNull PersonalInfoSearchVo searchVo) {
        // 构建查询条件
        QueryWrapper<PersonalInfo> queryWrapper = new QueryWrapper<>();
        if (searchVo.getIds() != null && searchVo.getIds().size() > 0) {
            return baseMapper.selectList(queryWrapper.in("id", searchVo.getIds()));
        }
        if (StringUtils.isNotBlank(searchVo.getIdentityJob())) {
            queryWrapper.eq("identity_job", searchVo.getIdentityJob());
        }
        if (StringUtils.isNotBlank(searchVo.getAgeGroup())) {
            queryWrapper.eq("age_group", searchVo.getAgeGroup());
        }
        if (StringUtils.isNotBlank(searchVo.getSex())) {
            queryWrapper.eq("sex", searchVo.getSex());
        }
        if (StringUtils.isNotBlank(searchVo.getEvaluationGrade())) {
            queryWrapper.eq("evaluation_grade", searchVo.getEvaluationGrade());
        }
        String socialPlatforms = searchVo.getSocialPlatforms();
        String fanZone = searchVo.getFanZone();
        if (StringUtils.isNotBlank(socialPlatforms) && StringUtils.isNotBlank(fanZone)) {
            if (socialPlatforms.equals("tiktok")) {
                queryWrapper.eq("tiktok", "有").eq("tiktok_fans", fanZone);
            } else if (socialPlatforms.equals("littleRedBook")) {
                queryWrapper.eq("little_red_book", "有").eq("little_red_book_fans", fanZone);
            } else if (socialPlatforms.equals("otherPlatforms")) {
                queryWrapper.eq("other_platforms", socialPlatforms);
            }
        } else if (StringUtils.isNotBlank(fanZone)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("tiktok_fans", searchVo.getFanZone())
                        .or()
                        .eq("little_red_book_fans", searchVo.getFanZone());
            });
        } else if (StringUtils.isNotBlank(socialPlatforms)) {
            if (socialPlatforms.equals("tiktok")) {
                queryWrapper.eq("tiktok", "有");
            } else if (socialPlatforms.equals("littleRedBook")) {
                queryWrapper.eq("little_red_book", "有");
            } else if (socialPlatforms.equals("otherPlatforms")) {
                queryWrapper.eq("other_platforms", socialPlatforms);
            }
        }
        if (StringUtils.isNotBlank(searchVo.getUserId())) {
            queryWrapper.like("user_id", searchVo.getUserId());
        }
        if (StringUtils.isNotBlank(searchVo.getUserName())) {
            queryWrapper.like("user_name", searchVo.getUserName());
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 获取测评师列表
     * @param searchVo
     * @return
     */
    @Override
    public List<PersonalInfo> getList(PersonalInfoSearchVo searchVo) {

        LambdaQueryWrapper<PersonalInfo> queryWrapper = new LambdaQueryWrapper<>();

        // 测评师编号
        if(StrUtil.isNotBlank(searchVo.getId())){
            queryWrapper.eq(PersonalInfo::getId, searchVo.getId());
        }

        // 社交平台
        String socialPlatforms = searchVo.getSocialPlatforms();

        // 粉丝区间
        String fanZone = searchVo.getFanZone();

        // 平台 + 粉丝数
        if (StringUtils.isNotBlank(socialPlatforms) && StringUtils.isNotBlank(fanZone)) {
            if (socialPlatforms.equals("tiktok")) {// 抖音
                queryWrapper.eq(PersonalInfo::getTiktok, "有").eq(PersonalInfo::getTiktokFans, fanZone);

            } else if (socialPlatforms.equals("littleRedBook")) {// 小红书
                queryWrapper.eq(PersonalInfo::getLittleRedBook, "有").eq(PersonalInfo::getLittleRedBookFans, fanZone);

            } else if (socialPlatforms.equals("otherPlatforms")) {// 其他平台
                queryWrapper.eq(PersonalInfo::getOtherPlatforms, socialPlatforms);
            }

        } else if (StringUtils.isNotBlank(fanZone)) {
            // 粉丝数
            queryWrapper.and((wrapper) -> {
                wrapper.eq(PersonalInfo::getTiktokFans, searchVo.getFanZone())
                        .or()
                        .eq(PersonalInfo::getLittleRedBookFans, searchVo.getFanZone());
            });

        } else if (StringUtils.isNotBlank(socialPlatforms)) {
            // 平台
            if (socialPlatforms.equals("tiktok")) {
                queryWrapper.eq(PersonalInfo::getTiktok, "有");

            } else if (socialPlatforms.equals("littleRedBook")) {
                queryWrapper.eq(PersonalInfo::getLittleRedBook, "有");

            } else if (socialPlatforms.equals("otherPlatforms")) {
                queryWrapper.eq(PersonalInfo::getOtherPlatforms, socialPlatforms);
            }
        }

        // 测评师等级
        if(StrUtil.isNotBlank(searchVo.getEvaluationGrade())){
            queryWrapper.eq(PersonalInfo::getEvaluationGrade, searchVo.getEvaluationGrade());
        }

        // 平台ID
        if(StrUtil.isNotBlank(searchVo.getUserId())){
            queryWrapper.eq(PersonalInfo::getUserId, searchVo.getUserId());
        }

        // 关联手机
        if(StrUtil.isNotBlank(searchVo.getPhoneNumber())){
            queryWrapper.eq(PersonalInfo::getPhoneNumber, searchVo.getPhoneNumber());
        }

        // 性别
        if(StrUtil.isNotBlank(searchVo.getSex())){
            queryWrapper.eq(PersonalInfo::getSex, searchVo.getSex());
        }

        // 年龄层
        if(StrUtil.isNotBlank(searchVo.getAgeGroup())){
            queryWrapper.eq(PersonalInfo::getAgeGroup, searchVo.getAgeGroup());
        }

        // 个人身份
        if(StrUtil.isNotBlank(searchVo.getIdentityJob())){
            queryWrapper.eq(PersonalInfo::getIdentityJob, searchVo.getIdentityJob());
        }

        // 注册时间（时间段查询）
        String dateRange = searchVo.getDateRange();
        if (JSONUtil.isJson(dateRange)) {
            JSONObject jsonObject = JSON.parseObject(dateRange);
            String startDate = jsonObject.getString("startDate");
            String endDate = jsonObject.getString("endDate");
            if (StrUtil.isNotBlank(startDate) && StrUtil.isNotBlank(endDate)) {
                // 比较两个时间的大小
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                if (LocalDate.parse(startDate, formatter).isAfter(LocalDate.parse(endDate, formatter))) {
                    throw new ServiceException("结束时间不能大于开始时间");
                }
                queryWrapper.apply("DATE(create_time) BETWEEN '" + startDate + "' AND '" + endDate + "'");
            }
        }

        queryWrapper.orderByDesc(PersonalInfo::getCreateTime);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<PersonalInfo> findByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    public AjaxResult editEvaluationGrade(@NonNull List<String> ids, String evaluationGrade) {
        if (ids.size() == 0) {
            return AjaxResult.success();
        }
        LambdaUpdateWrapper<PersonalInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(PersonalInfo::getId, ids);
        updateWrapper.set(PersonalInfo::getEvaluationGrade, evaluationGrade);
        baseMapper.update(null, updateWrapper);
        return AjaxResult.success();
    }

    @Override
    public PersonalInfo selectByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        return baseMapper.selectOne(new LambdaUpdateWrapper<PersonalInfo>()
                .eq(PersonalInfo::getUserId, userId));
    }


    /**
     * 校验【测评师资料】资料是否填写完毕
     *
     * @param userId 用户id
     * @return 查询结果
     */
    @Override
    public Boolean checkEvaluatorInfoFinish(String userId) {

        LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PersonalInfo::getUserId, userId);
        PersonalInfo personalInfo = baseMapper.selectOne(wrapper);

        if (BeanUtil.isEmpty(personalInfo)) {
            return false;
        }

        if (StrUtil.isBlank(personalInfo.getMainCategory()) || StrUtil.isBlank(personalInfo.getSecondCategory()) || StrUtil.isBlank(personalInfo.getInterests())) {
            return false;
        }

        if (StrUtil.isBlank(personalInfo.getTiktok()) || StrUtil.isBlank(personalInfo.getLittleRedBook())) {
            return false;
        }

        // 判断是否有抖音，有，则检验粉丝数、获赞数
        if ("有".equals(personalInfo.getTiktok())) {
            // System.out.println("****进入判断是否有抖音***");
            if (StrUtil.isBlank(personalInfo.getTiktokFans()) || StrUtil.isBlank(personalInfo.getTiktokLikes())) {
                return false;
            }
        }

        // 判断是否有小红书，有，则检验粉丝数、获赞数、收藏量
        if ("有".equals(personalInfo.getLittleRedBook())) {
            // System.out.println("****进入判断是否有小红书***");
            if (StrUtil.isBlank(personalInfo.getLittleRedBookFans()) || StrUtil.isBlank(personalInfo.getLittleRedBookLikes())) {
                return false;
            }
        }

        /*// 遍历JSONObject时，跳过以下字段
        String FieldNames = "id,createTime,updateTime,tiktokFans,tiktokLikes,littleRedBookFans,littleRedBookLikes,evaluationGrade,shoppingGroup,potentialConsumer,willingDistribute,openid,unionid,subscriptionOpenid,OtherPlatforms";

        JSONObject infoObject = JSON.parseObject(JSON.toJSONString(personalInfo), JSONObject.class);

        // 遍历JSONObject
        Iterator iter = infoObject.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
            String key = entry.getKey().toString();
            if (FieldNames.contains(key)) {
                // System.out.println("****是否跳过以下字段***key=" + key);
                continue;
            }

            if (entry.getValue() != null) {
                String value = entry.getValue().toString();
                // System.out.println("********"+ value + "=" + value);
                if (StrUtil.isBlank(value)) {
                    return false;
                }
            } else {
                return false;
            }
        }*/

        return true;
    }


    /** **************************** 以下是工具函数 *************************************** */

    /**
     * 获取随机数
     *
     * @param min
     * @param max
     * @return
     */
    public int getRandomIntRange(int min, int max) {
        Random random = new Random();
        return random.ints(min, (max + 1)).limit(1).findFirst().getAsInt();
    }

    @Override
    public TimerTask execute(BusinessDto business) {
        return new TimerTask() {
            @Override
            public void run() {
                //查询所有手机号不为空的用户
                LambdaQueryWrapper<PersonalInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.ne(PersonalInfo::getPhoneNumber,"");
                wrapper.isNotNull(PersonalInfo::getPhoneNumber);
                List<PersonalInfo> userList = list(wrapper);
                //为防止消息过大，分批发送
                int batchSize = 1000;
                int totalSize = userList.size();
                for (int i = 0; i < totalSize; i += batchSize) {
                    int endIndex = Math.min(i + batchSize, totalSize);
                    List<JSONObject> sendList = new ArrayList<>();
                    userList.subList(i, endIndex).forEach(user -> {
                        JSONObject sendTo = new JSONObject();
                        sendTo.put("sendTo",user.getRealName());
                        sendTo.put("phoneNumber",user.getPhoneNumber());
                        sendList.add(sendTo);
                    });
                    JSONObject object = business.getParams();
                    object.put("sendParam",sendList);
                    //将消息发送回
                    String exchange = RabbitEnums.COMPONET_SMS.getExchange();
                    String routeKey = RabbitEnums.COMPONET_SMS.getRoutingKey();
                    rabbitTemplate.convertAndSend(exchange, routeKey, object, message -> {
                        message.getMessageProperties().setHeader("x-delay", 0);
                        return message;
                    });;
                }
            }
        };
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        BusinessServiceFactory.register("personalInfoService", this);
    }
}
